package com.xdf.wxbebarrel.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdf.wxbebarrel.model.templateMessage.WebAuthorityAccessTokenRes;
import com.xdf.wxbebarrel.model.templateMessage.WebAuthorityUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author chanchaw
 * @create 2022-11-24 14:18
 */
@Component
public class WechatWebAuthorityUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 传入用户授权页面的code，返回请求来的微信用户信息
     * @param code 网页授权页面的 code
     * @return 微信用户信息
     */
    public static WebAuthorityUserInfo getWebAuthorityUserInfo(String code){
        /*
         * 当下面方法返回  WebAuthorityAccessTokenRes{
         *  access_token='null', expires_in=null, refresh_token='null', openid='null',
         *  scope='null', errcode=40163, errmsg='code been used, rid: 63f9ee02-57a21d8c-62099a87'}
         *  表示前端页面的 code 已经使用过了，不可再次使用，要提示用户重新打开页面重新提交
         */
        WebAuthorityAccessTokenRes webAuthorityAccessTokenRes = getWebAuthorityAccessTokenRes(code);
        if(webAuthorityAccessTokenRes == null) {
            String msg = "新用户注册,code:" + code + ",根据code请求accessToken时,响应来null," + new Date().toString() + ",log_runtime表中查询：module=新用户注册";
            //devTools.pushMsg6(msg);
            return null;
        }
        // 处理错误代码
        resolveErrorCode(webAuthorityAccessTokenRes.getErrcode());

        String accessToken = Optional.ofNullable(webAuthorityAccessTokenRes.getAccess_token()).orElse("");
        if(accessToken.length()<=0 || "null".equalsIgnoreCase(accessToken)){
            String msg = "新用户注册,code:" + code + ",根据code请求accessToken时,响应来的accessToken是null," + new Date().toString() + ",log_runtime表中查询：module=新用户注册";
            //devTools.pushMsg6(msg);
            return null;
        }

        String openId = Optional.ofNullable(webAuthorityAccessTokenRes.getOpenid()).orElse("");
        return getWebAuthorityUserInfo(accessToken, openId);
    }

    private static <T> T getWechatRes(String url,Class<T> clazz){
        String jsonString =  HttpUtils.sendGet(url);
        try {
            return mapper.readValue(jsonString, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    // 使用用户在前端页面的 code 获取网页授权的 access_token
    public static WebAuthorityAccessTokenRes getWebAuthorityAccessTokenRes(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+
                DevMaterial.JZY.APPID+"&secret="+DevMaterial.JZY.APPSECRET+"&code="+code+"&grant_type=authorization_code";
        return getWechatRes(url,WebAuthorityAccessTokenRes.class);
    }


    // 使用网页授权的 accessToken 获取微信用户信息
    public static WebAuthorityUserInfo getWebAuthorityUserInfo(String accessToken,String openId){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
        return getWechatRes(url, WebAuthorityUserInfo.class);
    }

//    public void sendMaster(String mill,String clientSid,String clientName,String nickName,String openId,String realName){
//        // 2022年2月25日 14:09:36 修改为 dev 身份即有权限审核
//        List<UserWeixin> masters = userWeixinService.selectDevs();
//        if( masters.size()<=0 ) {
//            return;
//        }
//
//        // 遍历 masters 将微信 openid 构建为 list，进行批量推送
//        List<String> users = new ArrayList<>();
//        for(UserWeixin user:masters){
//            users.add(user.getWeixin_name());
//        }
//
//        String strDate = "";
//        try {
//            strDate = DatetimeUtil.formatDateTZ8(new Date().getTime());
//        }catch (Exception e){
//        }
//
//        Client client = clientService.selectFirst(mill,clientSid);
//        //mill = "染厂：" + mill;
//        String showMill = "染厂：" + mill;
//        String clientSidName = "染厂客户：" + clientSid + " - " + clientName;
//        //nickName = "微信昵称：" + nickName;
//
//        // 如果未查询到客户资料推送模板消息通知开发人员查询出错
//        String[] errMsg = new String[]{"构建审核消息时出错",mill,clientSidName,openId,"未能在云端查询到该客户","","",DatetimeUtil.formatDateTZ8(new Date().getTime())};
//        if( client == null ){
//            try {
//                //devTools.pushWxMsgDefaultTmp(errMsg,users);
//            } catch (IOException e) {
//            }
//            return;
//        }
//
//        String url = buildDtlUrl(mill,client.getId(),clientSid,clientName,nickName,openId,new Date(),realName);
//        url = devTools.generateUrl(url);
//        String[] msg = new String[]{mill + ",realName:" + realName,clientName,nickName,openId,strDate,"","",url};
//        try{
//            devTools.pushWxMsgDefaultTmp(msg,users);
//        }catch(Exception e){
//        }
//    }

    // 构建推送的消息详情页链接（等待审核的模板消息）
    private static String buildDtlUrl(String mill,int clientId,String clientSid,String clientName,
                                      String nickName,String openId,Date followTime,String realName){
        return "https://www.xdfznh.club/wxpadfe/auditUser?mill=" + mill + "&clientId=" + clientId+
                "&clientSid=" + clientSid + "&clientName=" + clientName + "&nickName=" + nickName+
                "&openId=" + openId + "&followTime=" + followTime + "&realName=" + realName;
    }

    public static void resolveErrorCode(Integer errorCode){
        if(errorCode == null) return;
        String msg = "";
        switch (errorCode){
            case 40163:
                msg = "code已过期，请重新进入本页面！";
                break;
            case 40029:
                msg = "code无效，请重新进入本页面！";
                break;
            default:
                msg = "";
        }
        if(msg.length() > 0)
            throw new BusinessException(msg);
    }
}
